package com.cloud.rdui;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RandomName {

    public static String getName(boolean male) {

        return firstName() + secondName(male);
    }

    /*
     * 随机返回a和b其中一个数
     */
    public static int randomAB(int a, int b) {
        return (int) ((Math.random() * Math.abs(a - b)) + Math.min(a, b));
    }

    /**
     * 生成姓氏
     * @throws IOException
     */
    private static String firstName() {
        List<String> fistNames = loadBaiJiaXing("/asserts/百家姓");

        return fistNames.get(randomAB(0, fistNames.size()));
    }

    /**
     * 读取姓氏文件，获取姓氏
     * @return
     * @throws IOException
     */
    private static List<String> loadBaiJiaXing(String path) {
        //使用类加载器来加载文件
        InputStream in = RandomName.class.getResourceAsStream(path);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //文件读取
        String line = null;
        //结果集合
        List<String> result = new ArrayList<>(200);
        while (true) {
            try {
                if (!((line = br.readLine()) != null)) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            line = line.trim();
            //使用空白字符分割
            String[] names = line.split("\\s+");
            result.addAll(Arrays.asList(names));
        }
        return result;
    }

    /**
     * @生成名字
     * @return
     * @throws IOException
     */
    private static String secondName(boolean male) {
        if (male) {
            List<String> names = null;
            try {
                names = loadNames("/asserts/男性");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return names.get(randomAB(0, names.size()));
        } else {
            List<String> names = null;
            try {
                names = loadNames("/asserts/女性");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return names.get(randomAB(0, names.size()));
        }
    }

    /**
     * 读取百家姓文件，获取名字
     * @return
     * @throws IOException
     */
    private static List<String> loadNames(String path) throws IOException {
        InputStream in = RandomName.class.getResourceAsStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        //文件读取
        String line = null;
        //结果集合
        List<String> result = new ArrayList<>(200);
        while ((line = br.readLine()) != null) {
            line = line.trim();
            //使用空白字符分割
            String[] names = line.split("\\s+");
            result.addAll(Arrays.asList(names));
        }
        return result;
    }

}
